<template>
  <div class="post-detail-container">
    <!-- 帖子内容区域 -->
    <div class="post-content-area" v-loading="loading">
      <el-card v-if="post" class="post-card">
        <div class="post-header">
          <h1 class="post-title">{{ post.title }}</h1>
          <div class="post-meta">
            <div class="author-info">
              <el-avatar :size="40" :src="post.author.avatar"></el-avatar>
              <span class="author-name">{{ post.author.username }}</span>
            </div>
            <div class="post-stats">
              <span class="post-time">发布于: {{ formatTime(post.createTime) }}</span>
              <span class="stat-item">
                <el-icon><view /></el-icon>
                {{ post.viewCount }} 浏览
              </span>
              <span class="stat-item">
                <el-icon><chat-dot-round /></el-icon>
                {{ post.commentCount }} 评论
              </span>
            </div>
          </div>
        </div>

        <div class="post-tags">
          <el-tag v-for="tag in post.tags" :key="tag" size="small" class="tag">{{ tag }}</el-tag>
        </div>

        <div class="post-content">
          {{ post.content }}
        </div>

        <div class="post-actions">
          <el-button 
            :type="post.isLiked ? 'primary' : 'default'" 
            :icon="post.isLiked ? 'Star' : 'StarFilled'" 
            @click="toggleLike"
          >
            {{ post.likeCount }} 点赞
          </el-button>
          <el-button 
            :type="post.isCollected ? 'primary' : 'default'" 
            :icon="post.isCollected ? 'Collection' : 'CollectionTag'" 
            @click="toggleCollect"
          >
            收藏
          </el-button>
          <el-button 
            type="primary" 
            @click="scrollToComment"
          >
            <el-icon><chat-dot-round /></el-icon> 评论
          </el-button>
        </div>
      </el-card>

      <!-- 评论区域 -->
      <div class="comment-section" id="comment-section">
        <h2 class="section-title">评论 ({{ comments.length }})</h2>
        
        <!-- 评论输入框 -->
        <div class="comment-input" v-if="userStore.token">
          <el-input
            v-model="commentContent"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
          ></el-input>
          <div class="comment-submit">
            <el-button type="primary" @click="submitComment" :loading="submitting">
              发表评论
            </el-button>
          </div>
        </div>
        <el-alert
          v-else
          title="请先登录后再评论"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <el-button type="primary" size="small" @click="goToLogin">
              去登录
            </el-button>
          </template>
        </el-alert>

        <!-- 评论列表 -->
        <div class="comment-list">
          <el-empty description="暂无评论" v-if="comments.length === 0"></el-empty>
          
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-user">
              <el-avatar :size="32" :src="comment.user.avatar"></el-avatar>
              <div class="comment-user-info">
                <span class="comment-username">{{ comment.user.username }}</span>
                <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
              </div>
            </div>
            <div class="comment-content">
              {{ comment.content }}
            </div>
            <div class="comment-actions">
              <span class="action-item" @click="replyToComment(comment)">
                <el-icon><chat-line-round /></el-icon> 回复
              </span>
              <span class="action-item" @click="likeComment(comment)">
                <el-icon><thumb-up /></el-icon> {{ comment.likeCount }}
              </span>
              <span class="action-item" v-if="canDeleteComment(comment)" @click="deleteComment(comment)">
                <el-icon><delete /></el-icon> 删除
              </span>
            </div>
            
            <!-- 回复列表 -->
            <div class="reply-list" v-if="comment.replies && comment.replies.length > 0">
              <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                <div class="comment-user">
                  <el-avatar :size="24" :src="reply.user.avatar"></el-avatar>
                  <div class="comment-user-info">
                    <span class="comment-username">{{ reply.user.username }}</span>
                    <span class="comment-time">{{ formatTime(reply.createTime) }}</span>
                  </div>
                </div>
                <div class="comment-content">
                  <span class="reply-to" v-if="reply.replyTo">回复 @{{ reply.replyTo }}：</span>
                  {{ reply.content }}
                </div>
              </div>
            </div>
            
            <!-- 回复输入框 -->
            <div class="reply-input" v-if="replyingTo === comment.id">
              <el-input
                v-model="replyContent"
                size="small"
                placeholder="回复评论..."
              >
                <template #append>
                  <el-button @click="submitReply(comment)">回复</el-button>
                </template>
              </el-input>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 相关推荐区域 -->
    <div class="related-posts">
      <h3 class="section-title">相关推荐</h3>
      <el-card v-for="item in relatedPosts" :key="item.id" class="related-post-card" @click="viewPost(item.id)">
        <div class="related-post-title">{{ item.title }}</div>
        <div class="related-post-meta">
          <span>{{ item.author.username }}</span>
          <span>{{ formatTime(item.createTime) }}</span>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store/userStore';
import { ElMessage } from 'element-plus';
import { View, ChatDotRound, ChatLineRound, ThumbUp, Delete } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 状态变量
const loading = ref(true);
const post = ref(null);
const comments = ref([]);
const relatedPosts = ref([]);
const commentContent = ref('');
const replyContent = ref('');
const replyingTo = ref(null);
const submitting = ref(false);

// 获取帖子详情
const fetchPostDetail = async () => {
  const postId = route.params.id;
  if (!postId) {
    ElMessage.error('帖子ID不存在');
    router.push('/community');
    return;
  }

  loading.value = true;
  try {
    // 模拟API调用
    setTimeout(() => {
      post.value = {
        id: postId,
        title: `详细的帖子标题 ${postId}`,
        content: `这是一个详细的帖子内容。这里可以包含很多段落的文字，描述用户想要分享的内容。
        
        可以包含多个段落，讨论各种话题。这是帖子 ${postId} 的详细内容。
        
        这里是更多的内容段落，用户可以在这里详细阐述自己的观点和想法。`,
        createTime: new Date(Date.now() - Math.floor(Math.random() * 10000000)),
        author: {
          id: 101,
          username: '用户名' + Math.floor(Math.random() * 1000),
          avatar: `https://placekitten.com/200/200?image=${Math.floor(Math.random() * 16)}`
        },
        viewCount: Math.floor(Math.random() * 1000),
        commentCount: Math.floor(Math.random() * 50),
        likeCount: Math.floor(Math.random() * 100),
        isLiked: Math.random() > 0.5,
        isCollected: Math.random() > 0.5,
        tags: ['话题' + Math.floor(Math.random() * 5), '分类' + Math.floor(Math.random() * 3)]
      };
      
      // 模拟评论数据
      comments.value = Array(Math.floor(Math.random() * 5) + 2).fill().map((_, index) => ({
        id: index + 1,
        content: `这是评论 ${index + 1} 的内容。用户可以在这里发表自己的看法和意见。`,
        createTime: new Date(Date.now() - Math.floor(Math.random() * 10000000)),
        user: {
          id: 200 + index,
          username: '评论用户' + Math.floor(Math.random() * 1000),
          avatar: `https://placekitten.com/200/200?image=${Math.floor(Math.random() * 16)}`
        },
        likeCount: Math.floor(Math.random() * 20),
        replies: Array(Math.floor(Math.random() * 3)).fill().map((_, replyIndex) => ({
          id: `${index}-${replyIndex}`,
          content: `这是对评论 ${index + 1} 的回复 ${replyIndex + 1}。`,
          createTime: new Date(Date.now() - Math.floor(Math.random() * 5000000)),
          user: {
            id: 300 + replyIndex,
            username: '回复用户' + Math.floor(Math.random() * 1000),
            avatar: `https://placekitten.com/200/200?image=${Math.floor(Math.random() * 16)}`
          },
          replyTo: Math.random() > 0.5 ? '某用户' : null
        }))
      }));
      
      // 模拟相关帖子
      relatedPosts.value = Array(5).fill().map((_, index) => ({
        id: Number(postId) + index + 1,
        title: `相关帖子 ${index + 1}`,
        createTime: new Date(Date.now() - Math.floor(Math.random() * 10000000)),
        author: {
          id: 400 + index,
          username: '用户' + Math.floor(Math.random() * 1000)
        }
      }));
      
      loading.value = false;
    }, 500);
    
    // 实际API调用应该类似：
    // const response = await request.get(`/api/posts/${postId}`);
    // post.value = response;
    // const commentsRes = await request.get(`/api/posts/${postId}/comments`);
    // comments.value = commentsRes.data;
    // const relatedRes = await request.get(`/api/posts/${postId}/related`);
    // relatedPosts.value = relatedRes.data;
  } catch (error) {
    console.error('获取帖子详情失败:', error);
    ElMessage.error('获取帖子详情失败');
    loading.value = false;
  }
};

// 格式化时间
const formatTime = (time) => {
  const date = new Date(time);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 点赞帖子
const toggleLike = () => {
  if (!userStore.token) {
    ElMessage.warning('请先登录');
    return;
  }
  
  post.value.isLiked = !post.value.isLiked;
  if (post.value.isLiked) {
    post.value.likeCount++;
    ElMessage.success('点赞成功');
  } else {
    post.value.likeCount--;
    ElMessage.info('已取消点赞');
  }
  
  // 实际API调用应该类似：
  // await request.post(`/api/posts/${post.value.id}/like`, { liked: post.value.isLiked });
};

// 收藏帖子
const toggleCollect = () => {
  if (!userStore.token) {
    ElMessage.warning('请先登录');
    return;
  }
  
  post.value.isCollected = !post.value.isCollected;
  if (post.value.isCollected) {
    ElMessage.success('收藏成功');
  } else {
    ElMessage.info('已取消收藏');
  }
  
  // 实际API调用应该类似：
  // await request.post(`/api/posts/${post.value.id}/collect`, { collected: post.value.isCollected });
};

// 滚动到评论区
const scrollToComment = () => {
  document.getElementById('comment-section').scrollIntoView({ behavior: 'smooth' });
};

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('评论内容不能为空');
    return;
  }
  
  submitting.value = true;
  try {
    // 模拟API调用
    setTimeout(() => {
      const newComment = {
        id: comments.value.length + 1,
        content: commentContent.value,
        createTime: new Date(),
        user: {
          id: userStore.userInfo?.id || 999,
          username: userStore.userInfo?.username || '当前用户',
          avatar: userStore.userInfo?.avatar || 'https://placekitten.com/200/200'
        },
        likeCount: 0,
        replies: []
      };
      
      comments.value.unshift(newComment);
      post.value.commentCount++;
      commentContent.value = '';
      ElMessage.success('评论发表成功');
      submitting.value = false;
    }, 300);
    
    // 实际API调用应该类似：
    // await request.post(`/api/posts/${post.value.id}/comments`, { content: commentContent.value });
    // 然后重新获取评论列表
  } catch (error) {
    console.error('发表评论失败:', error);
    ElMessage.error('发表评论失败');
    submitting.value = false;
  }
};

// 回复评论
const replyToComment = (comment) => {
  if (!userStore.token) {
    ElMessage.warning('请先登录');
    return;
  }
  
  replyingTo.value = comment.id;
  replyContent.value = '';
};

// 提交回复
const submitReply = async (comment) => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('回复内容不能为空');
    return;
  }
  
  try {
    // 模拟API调用
    setTimeout(() => {
      const newReply = {
        id: `${comment.id}-${comment.replies.length + 1}`,
        content: replyContent.value,
        createTime: new Date(),
        user: {
          id: userStore.userInfo?.id || 999,
          username: userStore.userInfo?.username || '当前用户',
          avatar: userStore.userInfo?.avatar || 'https://placekitten.com/200/200'
        },
        replyTo: comment.user.username
      };
      
      if (!comment.replies) {
        comment.replies = [];
      }
      
      comment.replies.push(newReply);
      replyingTo.value = null;
      replyContent.value = '';
      ElMessage.success('回复成功');
    }, 300);
    
    // 实际API调用应该类似：
    // await request.post(`/api/comments/${comment.id}/replies`, { content: replyContent.value });
    // 然后重新获取评论列表
  } catch (error) {
    console.error('回复评论失败:', error);
    ElMessage.error('回复评论失败');
  }
};

// 点赞评论
const likeComment = (comment) => {
  if (!userStore.token) {
    ElMessage.warning('请先登录');
    return;
  }
  
  comment.likeCount++;
  ElMessage.success('点赞成功');
  
  // 实际API调用应该类似：
  // await request.post(`/api/comments/${comment.id}/like`);
};

// 删除评论
const deleteComment = async (comment) => {
  try {
    // 模拟API调用
    setTimeout(() => {
      comments.value = comments.value.filter(item => item.id !== comment.id);
      post.value.commentCount--;
      ElMessage.success('评论已删除');
    }, 300);
    
    // 实际API调用应该类似：
    // await request.delete(`/api/comments/${comment.id}`);
    // 然后重新获取评论列表
  } catch (error) {
    console.error('删除评论失败:', error);
    ElMessage.error('删除评论失败');
  }
};

// 判断是否可以删除评论
const canDeleteComment = (comment) => {
  const userId = userStore.userInfo?.id;
  return userId && (userId === comment.user.id || userStore.userInfo?.role === 'admin');
};

// 查看其他帖子
const viewPost = (postId) => {
  router.push(`/post/${postId}`);
};

// 跳转到登录页
const goToLogin = () => {
  router.push('/login');
};

// 组件挂载时获取数据
onMounted(() => {
  fetchPostDetail();
});
</script>

<style scoped>
.post-detail-container {
  display: flex;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  gap: 20px;
}

.post-content-area {
  flex: 1;
}

.post-card {
  margin-bottom: 20px;
}

.post-header {
  margin-bottom: 20px;
}

.post-title {
  margin-bottom: 15px;
  font-size: 1.8rem;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-name {
  font-weight: 500;
}

.post-stats {
  display: flex;
  gap: 15px;
  color: #909399;
}

.post-time {
  font-size: 0.9rem;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.post-tags {
  margin: 15px 0;
}

.tag {
  margin-right: 8px;
}

.post-content {
  margin: 20px 0;
  line-height: 1.6;
  white-space: pre-line;
}

.post-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
  justify-content: flex-end;
}

.section-title {
  margin: 20px 0;
  font-size: 1.2rem;
  font-weight: 500;
  color: #303133;
}

.comment-input {
  margin-bottom: 20px;
}

.comment-submit {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.comment-user {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.comment-user-info {
  display: flex;
  flex-direction: column;
}

.comment-username {
  font-weight: 500;
}

.comment-time {
  font-size: 0.8rem;
  color: #909399;
}

.comment-content {
  margin: 10px 0;
  line-height: 1.5;
}

.comment-actions {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  cursor: pointer;
}

.action-item:hover {
  color: #409eff;
}

.reply-list {
  margin-left: 40px;
  margin-top: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.reply-item {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.reply-item:last-child {
  border-bottom: none;
}

.reply-to {
  color: #409eff;
  margin-right: 5px;
}

.reply-input {
  margin-top: 10px;
  margin-left: 40px;
}

.related-posts {
  width: 300px;
}

.related-post-card {
  margin-bottom: 10px;
  cursor: pointer;
}

.related-post-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.related-post-title {
  font-weight: 500;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.related-post-meta {
  display: flex;
  justify-content: space-between;
  font-size: 0.8rem;
  color: #909399;
}

@media (max-width: 768px) {
  .post-detail-container {
    flex-direction: column;
  }
  
  .related-posts {
    width: 100%;
  }
}
</style>